﻿using System;
using DG.Tweening;
using UI;
using UnityEngine;

public class InteractRole : MonoBehaviour
{
    public string m_name;
    public float m_followDis = 1.5f;
    public float m_followSpeed = 7.5f;

    public string m_triggerScenario;
    
    private Transform m_target;
    private Vector3 m_lastPosition;
    
    private static readonly int Moving = Animator.StringToHash("moving");
    private static readonly int Bubble = Animator.StringToHash("bubble");

    private bool m_trigger;
    
    private Animator m_animator;
    private SpriteRenderer m_spriteRenderer;
    private void Awake()
    {
        m_animator = GetComponent<Animator>();
        m_spriteRenderer = transform.Find("Model").GetComponent<SpriteRenderer>();
    }
    private void FixedUpdate()
    {
        if (m_target != null && m_target.position != m_lastPosition)
        {
            var delta = m_target.position - transform.position;
            if (delta.sqrMagnitude >= m_followDis * m_followDis)
            {
                transform.position += delta.normalized * (m_followSpeed * Time.fixedDeltaTime);
                m_animator.SetBool(Moving, true);
            }
            else
            {
                m_animator.SetBool(Moving, false);
            }
            m_spriteRenderer.flipX = delta.x < 0;
        }
        else
        {
            m_animator.SetBool(Moving, false);
        }
    }
    public void SetFollow(Transform target)
    {
        m_target = target;
        m_lastPosition = target.position;
        
        var delta = m_target.position - transform.position;
        m_spriteRenderer.flipX = delta.x < 0;
        
        UI_TipPanel.ShowTip($"{m_name}加入队伍");
    }

    private void OnTriggerEnter2D(Collider2D other)
    {
        if (string.IsNullOrEmpty(m_triggerScenario) || m_trigger || other.gameObject.layer != Layers.Player) return;
        m_trigger = true;
        
        var delta = other.transform.position - transform.position;
        m_spriteRenderer.flipX = delta.x < 0;
        
        PlayerController.SetPause(true);
        transform.DOLocalMoveY(1.5f, 0.25f).SetRelative(true).SetLoops(2, LoopType.Yoyo).OnComplete(() =>
        {
            PlayerController.SetPause(false);
            UI_ScenarioPanel.StartScenario(m_triggerScenario);
        });
    }
}